Ext.define("Triends.controller.Controller", {

    extend: "Ext.app.Controller",
    config: {
        refs: {
            main: "main",
            ting: "#ting",
            triends: "#triends",
            account: "#account",
            settings: "#settings"
        },
        control: {
        	main: {
				activeitemchange: function(container, value, oldValue, eOpts ) {
					Triends.app.getHistory().add(Ext.create('Ext.app.Action', {
            			url: 'mainpage'
        			}));
				}
            },
            ting: {
            	deactivate: function(oldActiveItem, container, newActiveItem, eOpts) {
					oldActiveItem.setActiveItem(0);
				}
            },
            triends: {
            	deactivate: function(oldActiveItem, container, newActiveItem, eOpts) {
					oldActiveItem.setActiveItem(0);
				}
            },
            account: {
            	deactivate: function(oldActiveItem, container, newActiveItem, eOpts) {
					oldActiveItem.setActiveItem(0);
				}
            },
            settings: {
            	deactivate: function(oldActiveItem, container, newActiveItem, eOpts) {
					oldActiveItem.setActiveItem(0);
				}
            }
        },
        routes: {
        	'login': 'login',
        	'join': 'join',
        	'mainpage': 'reset',
            'mainpage/:a/:b' : 'changeView',
            'tinginfo/:a/:b' : 'tinginfoview',  //'tinginfo/account/42'
            'otherinfo/:a/:b/:c' : 'otherinfoview', //'otherinfo/account/ID
 			'tingmodify/:a' : 'tingmodifyview'	
            }
    },
    login: function() {
    	var login = Ext.create('login');
    	Ext.Viewport.setActiveItem(login);
    },
    join: function() {
    	var join = Ext.create('join');
	    var response = Ext.getCmp('agrmtconfirm').getData();
	    Ext.getCmp('join').setData(response);
	     Ext.Viewport.setActiveItem(join);
	    Ext.getCmp('agrmtconfirm').destroy();
	   
    },
    reset: function() {
    	this.getMain().getActiveItem().setActiveItem(0);
    },
	changeView: function(a, b) {
    	this.getMain().setActiveItem(Ext.getCmp(a));
    	Ext.getCmp(a).setActiveItem(Ext.getCmp(b));
    },
    tinginfoview: function(a, b) {
    	Ext.Viewport.setMasked({
    		xtype: 'loadmask',
    		indicator: true
    	});
    	
    	var tingnum = b;
    	var tinginfoStore = Ext.getStore('tinginfoStore'+tingnum);
    	var hostRecord = tinginfoStore.getAt(0);	
		
		var activetab = Ext.getCmp(a);
		var tinginfo;
		
		if (Ext.typeOf(Ext.getCmp('tinginfo')) == 'object') {
			tinginfo = Ext.getCmp('tinginfo');
		} else {
			tinginfo = Ext.create('Triends.view.Tinginfo');
		}
		activetab.add(tinginfo);
		activetab.setActiveItem(tinginfo);
		
		var addresslat = hostRecord.getData().LAT; // 지도 주소 보여주기 Reverse Geocoding
		var addresslng = hostRecord.getData().LNG;
		var addresslatlng = new google.maps.LatLng(addresslat, addresslng);
		geocoder.geocode({'latLng':addresslatlng}, function(results, status){
			if (status == google.maps.GeocoderStatus.OK) {
            	if (results[1]) {
            		address = results[1].formatted_address;
			 		var addresspanel = Ext.getCmp('addresspanel');
			 		addresspanel.setHtml(address);
            	}
			}
		});
		
		var splitcontent = hostRecord.getData().CONTENT.split('<br>');
		var tworowscontent;
		if (splitcontent[1] == null){
			tworowscontent = splitcontent[0]
		} else {
			tworowscontent = splitcontent[0].concat('<br>', splitcontent[1]);
		}
 		var tingcontentpanel = Ext.getCmp("tingcontentpanel");
 		var tingcontentpanel2 = Ext.getCmp("tingcontentpanel2");
 		tingcontentpanel.setHtml("<font size='3'>"+tworowscontent+"</font>")
 		tingcontentpanel.setData(hostRecord.getData());
 		tingcontentpanel2.setData(tworowscontent);
		
 		
 		var tingtitlepanel = Ext.getCmp("tingtitlepanel");
 		var tinginfotheme = Ext.getCmp('tinginfotheme');
 		var tingtimepanel = Ext.getCmp("tingtimepanel");
 		var tinghostpanel = Ext.getCmp('tinghostpanel');
		var tifipanel = Ext.getCmp('tifipanel'); 	
 		var tinginfotfipicture = Ext.getCmp('tinginfotfipicture');
 		var tinginfotfipanel = Ext.getCmp("tinginfotfipanel");
 		var hostpanel = Ext.getCmp("hostpanel");
 		
 		var Tvalue = hostRecord.getData().Total;
 		var Tvaluepic = hostRecord.getData().Wifi;
// 		var tinghostdata = Ext.getStore('TriendsStore').findRecord('ID', hostRecord.getData().ID);
 		var tingdate = hostRecord.getData().DATE.substr(0, 10);
 		var hour = hostRecord.getData().DATE.substr(11, 2);
 		var minute = hostRecord.getData().DATE.substr(13);
 		var ampm;
		if(hour >= 12){
			hour = hour-12;
			ampm = "PM"
		} else{
			ampm = "AM"
		}
 		tingtitlepanel.setData(hostRecord.getData());
 		tinginfotheme.setSrc('resource/images/'+hostRecord.getData().THEME+'.png');
 		tingtimepanel.setHtml("<div align='right' style='margin-right:10px'><font size='3'>"+tingdate+"<br>"+ampm+" "+hour+""+minute+"</font></div>");
 		tinghostpanel.setData(hostRecord.getData()); // tinginfo에서 data받기 위해서
 		tifipanel.setData(hostRecord.getData());
 		tinginfotfipanel.setHtml(Tvalue+"%");
		tinginfotfipicture.setHtml("<img src='resource/images/wifi"+Tvaluepic+".png' width='40px' height='40px'>");
 		
 		
 		// 주인장 정보 표시하기
		var otherid = hostRecord.getData().ID;
 		var userlat = UserStore.getAt(0).data.UserLat;
        var userlng = UserStore.getAt(0).data.UserLng;
    	var usertheme = UserStore.getAt(0).data.UserTheme;
    	var usertime = UserStore.getAt(0).data.UserTime;
    	
    	Ext.getStore('TingHostStore').removeAll();
        Ext.data.JsonP.request({
    	url: 'http://itscreater.cafe24.com/Triends/Othersinfo.jsp',
        params: {id: otherid, userlat: userlat, userlng: userlng, usertheme: usertheme},
        callbackKey: 'callback',
            success: function(result) {
            	Ext.getStore('TingHostStore').setData(result);
            }
        });
 		
 		
 		// 참가자, 댓글, 버튼 표시하기.
 		// 스토어 로드
		var AttendeeStore = Ext.getStore('AttendeeStore'+tingnum);
		var TingCommentStore = Ext.getStore('TingCommentStore'+tingnum);
		
		// 버튼 로드
		var tingjoinbtn = Ext.getCmp("tingjoinbtn");
        var tingjcancelbtn = Ext.getCmp("tingjoincancelbtn");
	    var tingdelbtn = Ext.getCmp("tingdeletebtn");
	    var tingmdfbtn = Ext.getCmp("tingmodifybtn");
	    var joinpanel = Ext.getCmp('joinpanel');
	    var tinginfotitle = Ext.getCmp('tinginfotitle');
		var userid = Ext.getStore("UserStore").getAt(0).data.ID;
		
		// user가 host인 경우
		if (hostRecord.data.ID == userid) {
			joinpanel.setHidden(true);
			tinginfotitle.setHidden(false);
		   	tingdelbtn.setHidden(false);  
		   	tingmdfbtn.setHidden(false);
		}		
		
		// 데이터 통신 
        	
		Ext.data.JsonP.request({
		   	url: 'http://itscreater.cafe24.com/Triends/AttendeeList.jsp',
		    params: {num: tingnum, userlat: userlat, userlng: userlng, usertheme: usertheme},
		    callbackKey: 'callback',
		    success: function(result) {
		    	
		    	// 참가자 리스트 새로운 데이터 바인딩
				AttendeeStore.setData(result);
				var attendeelistpanel = Ext.getCmp('attendeelistpanel');
				attendeelistpanel.setStore(AttendeeStore);
				attendeelistpanel.refresh();
				
				// 버튼 표시 여부 결정
				if (hostRecord.data.ID != userid) {
	    			var joincheck = 0;
					AttendeeStore.each( function(model) {
						if (model.data.ID == userid) {
							joincheck++;
						}
					});
					if (joincheck == 0) { // join안되어있을 경우
						joinpanel.setHidden(false);
						joinpanel.items.items[0].setHtml('<font size="2">You have not joined</font>');
						tinginfotitle.setHidden(true);
		    			tingdelbtn.setHidden(true);
		        		tingmdfbtn.setHidden(true);
		        		tingjoinbtn.setHidden(false);
		        		tingjcancelbtn.setHidden(true);
		    		} else { // join 되어있을 경우
		    			joinpanel.setHidden(false);
		    			
		    			joinpanel.items.items[0].setHtml('<font size="2">You have joined</font>');
		    			tinginfotitle.setHidden(true);
			    		tingdelbtn.setHidden(true);
		       			tingmdfbtn.setHidden(true);
		       			tingjoinbtn.setHidden(true);
		       			tingjcancelbtn.setHidden(false);
		    		}
				}
			}
		});
		    
		// 댓글 데이터 로드
		Ext.data.JsonP.request({
			url: 'http://itscreater.cafe24.com/Triends/TingCommentList.jsp',
			params: {num: tingnum},
			callbackKey: 'callback',
			success: function(result) {
				
				// 댓글 새로운 데이터 바인딩
				TingCommentStore.setData(result);
				var TingComment = Ext.getCmp('tingcomment');
				TingComment.setStore(TingCommentStore);
				TingComment.refresh();
			}
		});
	
	Ext.Viewport.setMasked(false);
},
    tingmodifyview: function(a) {
    	
		Ext.Viewport.setMasked({
			xtype: 'loadmask',
    		indicator: true
		});
    	var activetab = Ext.getCmp(a);
    	
    	var tingmodify = Ext.create('Triends.view.TingModify');
    	
		var tingmdftitle = Ext.getCmp("tingmdftitle");
		var tingmdftheme = Ext.getCmp("tingmdftheme");
		var tingmdfdate = Ext.getCmp("tingmdfdate");
		var tingmdfcontent = Ext.getCmp("tingmdfcontent");
		var mdfthemeimage = Ext.getCmp('mdfthemeimage');
				
		var tinginfoData = Ext.getCmp("tinghostpanel").getData();
		Ext.getCmp('tingmodify').setData(tinginfoData);

		var num = tinginfoData.NUMBER;
		var tingtitledata = tinginfoData.TITLE;
							
		var tingthemedata = tinginfoData.THEME;
		var tingdatedata = new Date(tinginfoData.DATE);
		var tingcontentdata = tinginfoData.CONTENT;
					
		if (tingtitledata.match("&nbsp;") != null){
			tingtitledata = tingtitledata.replace(/&nbsp;/gi, " "); /*/gi를 써서 전체 문자열을 바꿔준다 */
		}
		tingmdftitle.setValue(tingtitledata);
		tingmdftheme.setValue(tingthemedata);
		mdfthemeimage.setSrc('resource/images/'+tingthemedata+'.png');
		tingmdfdate.setValue(tingdatedata);
		
		var lat = Ext.getCmp("tingmodify").getData().LAT;
		var lng = Ext.getCmp("tingmodify").getData().LNG;
		var latlng = new google.maps.LatLng(lat, lng); 
		geocoder.geocode({'latLng':latlng}, function(results, status){
			if (status == google.maps.GeocoderStatus.OK) {
            	if (results[1]) {
            		var address = results[1].formatted_address;
			 		var tingmdflocation = Ext.getCmp('tingmdflocation');
			 		tingmdflocation.setHtml(address);
            	}
			}
		});
		
		if (tingcontentdata.match("<br>") != null || tingcontentdata.match("&nbsp;") != null){
			tingcontentdata = tingcontentdata.replace(/&nbsp;/gi, " "); /*/gi를 써서 전체 문자열을 바꿔준다 */
			tingcontentdata = tingcontentdata.replace(/<br>/gi, "\n");
		}								
		tingmdfcontent.setValue(tingcontentdata);
			
		activetab.add(tingmodify);
        activetab.setActiveItem(tingmodify);
        Ext.Viewport.setMasked(false);
    },
    otherinfoview: function(a, b, c) {
    	Ext.Viewport.setMasked({
			xtype: 'loadmask',
    		indicator: true
		});
		
    	var activetab = Ext.getCmp(a);
    	var otherid = b;
    	
    	
		var otherinfo;
		if (Ext.typeOf(Ext.getCmp('othersinfo')) == 'object') {
			otherinfo = Ext.getCmp('othersinfo');
		} else {
			otherinfo = Ext.create('Triends.view.Othersinfo');
			activetab.add(otherinfo);
		}
		
        activetab.setActiveItem(otherinfo);
        var FBbutton = Ext.getCmp('FBbutton');
  		FBbutton.setHtml("<a id= 'moveFB' href='https://m.facebook.com/" + otherid +"'>Go to Facebook</a>");//	
		var otherimg = Ext.getCmp('otherimg');
        otherimg.setHtml("<img src='https://graph.facebook.com/"+otherid+"/picture?width=130&height=130'>");
        
		var othersStore = Ext.getStore('OthersStore'+otherid);
    	var otherHOSTtingStore = Ext.getStore('otherHOSTtingStore'+otherid);
		var otherATTENDtingStore = Ext.getStore('otherATTENDtingStore'+otherid);
		
       	var userlat = UserStore.getAt(0).data.UserLat
        var userlng = UserStore.getAt(0).data.UserLng
    	var usertheme = UserStore.getAt(0).data.UserTheme;
    	
        Ext.data.JsonP.request({
    	url: 'http://itscreater.cafe24.com/Triends/Othersinfo.jsp',
        params: {id: otherid, userlat: userlat, userlng: userlng, usertheme: usertheme},
        callbackKey: 'callback',
            success: function(result) {
            	othersStore.setData(result);
            	
            	var otherlat = othersStore.getAt(0).data.UserLat;
  				var otherlng = othersStore.getAt(0).data.UserLng;
  				var otherlatlng = new google.maps.LatLng(otherlat, otherlng);
  				geocoder.geocode({'latLng':otherlatlng}, function(results, status){
					if (status == google.maps.GeocoderStatus.OK) {
            			if (results[1]) {
            				var othercityname = results[1].address_components[2].long_name;
			 				var otherlocationpanel = Ext.getCmp('otherlocationpanel');
			 				otherlocationpanel.setHtml("<font size='2'>"+othercityname+"</font>");
            			}
					}
				});
		
				var othertfi = othersStore.getAt(0).data.Total;
    			var othertfipic = othersStore.getAt(0).data.Wifi;
				var otherthemepanel = Ext.getCmp('otherthemepanel');
				otherthemepanel.setSrc('resource/images/'+othersStore.getAt(0).data.UserTheme+'.png');
				var othertfinamepanel = Ext.getCmp('othertfinamepanel');
				othertfinamepanel.setHtml('<div style="line-height:80%"><font size="2">'+othersStore.getAt(0).data.Name+'</font></div>');
				var othertfipanel = Ext.getCmp('othertfipanel');
				othertfipanel.setHtml(othertfi+'%');
				var otherinfotfipicture = Ext.getCmp("otherinfotfipicture");
				otherinfotfipicture.setHtml("<img src='resource/images/wifi"+othertfipic+".png' width='40px' height='40px'>");
				var othertfigetdata = Ext.getCmp("othertfigetdata")
				othertfigetdata.setData(othersStore.getAt(0));
		  		
		  		var otherinfoview = Ext.getCmp('otherinfoview');
		        otherinfoview.setStore(othersStore);
		        var otherintroview = Ext.getCmp('otherintroview');        
		        otherintroview.setStore(othersStore);
            			
           	    Ext.data.JsonP.request({
        			url: 'http://itscreater.cafe24.com/Triends/UserHostTing.jsp',
        			params: {
        				id: otherid,
						userlat: userlat, 
						userlng: userlng, 
						usertheme: usertheme
					},
        			callbackKey: 'callback',
        			success: function(result) {
            			for(i=0;i<result.length;i++){
							var date = result[i].DATE.split(' ')[0];
							var hour = result[i].DATE.split(' ')[1].substr(0,2);
							var minute = result[i].DATE.split(' ')[1].substr(2);
							var ampm;
							if(hour >= 12){
								hour = hour-12;
								ampm = "PM"
							} else{
								ampm = "AM"
							}
							var finaldate = date+" "+ampm+" "+hour+""+minute;
							result[i].AMPMDATE = finaldate; 
						}
						otherHOSTtingStore.setData(result);
						var otherHOSTting = Ext.getCmp('otherhosttingview');
        				otherHOSTting.setStore(otherHOSTtingStore);
						
            			Ext.data.JsonP.request({
        					url: 'http://itscreater.cafe24.com/Triends/UserAttendTing.jsp',
        					params: {
        						id: otherid,
								userlat: userlat, 
								userlng: userlng, 
								usertheme: usertheme
							},
        					callbackKey: 'callback',
        					success: function(result) {
        						for(i=0;i<result.length;i++){
									var date = result[i].DATE.split(' ')[0];
									var hour = result[i].DATE.split(' ')[1].substr(0,2);
									var minute = result[i].DATE.split(' ')[1].substr(2);
									var ampm;
									if(hour >= 12){
										hour = hour-12;
										ampm = "PM"
									} else{
										ampm = "AM"
									}
									var finaldate = date+" "+ampm+" "+hour+""+minute;
									result[i].AMPMDATE = finaldate;
								}
								otherATTENDtingStore.setData(result);
								 var otherATTENDting = Ext.getCmp('otherattendtingview');
        						otherATTENDting.setStore(otherATTENDtingStore);
        					}
    					});
        			}
    			});
            }
    	});
        Ext.Viewport.setMasked(false);
        
    }
});